import { call, put, fork, select, take } from 'redux-saga/effects'
import actions,{ SEND, GET_SIGN_DATA, IMPORT_FILE } from '@/actions/send'
import api from '@/api/send'
import { message } from 'antd'
import successDesc from '@/constants/success'

function* send() {
  try {
    const params = yield select(({ sendReducer:{ sign, fileData, messageContent: content, signType, phoneSelectTypes } }) => { 
      return {
        id: fileData.id,
        phoneTypes: phoneSelectTypes.join(','),
        sign,
        content,
        signType,
      }
    })
    if(!params.phoneTypes.length || !params.id) throw new Error('手机号码不能为空')
    const { isSuccess, desc} = yield call(api.send, params)
    if(isSuccess){
      yield put(actions.sendSuccess())
      message.success(successDesc.send)
    }else {
      throw new Error(desc)
    } 
  } catch (error) {
    yield put(actions.sendFail())
    message.error(error.message || '发送错误')
  }
}

function* getSignData() {
  try {
    const { isSuccess, data, desc } = yield call(api.getSignEnum)
    if(isSuccess){
      yield put(actions.getSignDataSuccess(data))
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.getSignDataFail())
    message.error(error.message || '获取签名错误')
  }
}

function* importFile({ file }) {
  try {
    const formdata = new FormData()
    formdata.append('file', file)
    const { isSuccess, data, desc } = yield call(api.importFile, formdata)
    if(isSuccess) {
      const fileName = file.name
      yield put(actions.importFileSuccess(data, fileName))
      message.success(successDesc.importFile)
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.importFileFail())
    console.log('error', error, error.message)
    message.error(error.message || '导入文件错误') 
  }
}

function* watchImportFile() {
  while (true) {
    const { file } = yield take(IMPORT_FILE)
    yield call(importFile, file)
  }
}

function* watchGetSignData() {
  while(true) {
    yield take(GET_SIGN_DATA)
    yield call(getSignData)
  }
}

function* watchSend() {
  while (true) {
    yield take(SEND)
    yield call(send)
  }
}

export default [
  fork(watchGetSignData),
  fork(watchImportFile),
  fork(watchSend),
]